@echo off
setlocal enabledelayedexpansion

:: 配置参数（可修改）
set "windowsPort=8000"
set "wslPort=80"
set "ruleName=WSL2-Port-Forward-%windowsPort%"

:: 检查是否以管理员身份运行
fltmc >nul 2>&1 || (
    echo Error: This script requires administrative privileges.
    echo Please right-click and select "Run as administrator".
    pause >nul
    exit /b 1
)

:: 获取 WSL2 IP 地址
echo Detecting WSL2 IP address...
for /f "tokens=1" %%i in ('wsl -- hostname -I 2^>nul') do (
    set "wslIp=%%i"
)

if "!wslIp!"=="" (
    echo Error: Failed to get WSL2 IP address. Ensure WSL2 is running.
    pause >nul
    exit /b 1
)
echo Detected WSL2 IP: !wslIp!
echo.

:: 删除旧的端口转发规则
echo Removing old port forwarding rule...
netsh interface portproxy delete v4tov4 listenport=%windowsPort% listenaddress=0.0.0.0 >nul 2>&1

:: 创建新的端口转发规则
echo Configuring new port forwarding rule: Windows %windowsPort% -> WSL2 !wslIp!:!wslPort!
netsh interface portproxy add v4tov4 ^
    listenport=%windowsPort% ^
    listenaddress=0.0.0.0 ^
    connectport=%wslPort% ^
    connectaddress=!wslIp! >nul 2>&1

:: 验证端口转发规则
netsh interface portproxy show all | findstr /r /c:"0.0.0.0.*%windowsPort%.*!wslIp!.*%wslPort%" >nul 2>&1
if %errorlevel% neq 0 (
    echo Error: Failed to create port forwarding rule.
    pause >nul
    exit /b 1
)

:: 删除旧的防火墙规则
echo Removing old firewall rule...
netsh advfirewall firewall delete rule name="%ruleName%" >nul 2>&1

:: 创建新的防火墙规则
echo Configuring firewall rule for port %windowsPort%...
netsh advfirewall firewall add rule ^
    name="%ruleName%" ^
    dir=in ^
    action=allow ^
    protocol=TCP ^
    localport=%windowsPort% ^
    profile=any >nul 2>&1

:: 验证防火墙规则
netsh advfirewall firewall show rule name="%ruleName%" >nul 2>&1
if %errorlevel% neq 0 (
    echo Firewall rule created successfully.
) else (
    echo Error: Failed to create firewall rule.
    pause >nul
    exit /b 1
)

:: 完成提示
echo.
echo ✅ All configurations completed!
echo You can access WSL2's port %wslPort% via http://localhost:%windowsPort%
echo.
pause >nul
